package com.sweets.look.ui.setting;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.io.File;

import com.sweet.satellite.GlobalConfig;
import com.sweet.satellite.TranslucentSBActivity;
import com.sweets.look.R;
import com.sweets.look.preference.PreferenceManager;
import com.sweets.look.ui.activity.FileBrowser;
import com.sweets.look.ui.browser.BookmarkManager;
import com.sweets.look.ui.widget.MarkRadioDialog;
import com.sweets.look.util.FileUtils;
import com.sweets.look.util.LogUtils;
import com.sweets.look.util.Utils;
import com.sweets.look.util.ViewUtils;

public class BookmarkSettings extends TranslucentSBActivity {
    private final static String TAG = BookmarkSettings.class.getSimpleName();

    private BookmarkManager mBookmarkManager;
    private Context mContext;
    private PreferenceManager mPreferences;
    private TextView mStyleText;
    private int operation = -1;


    private void bookmarksStyleSelect() {
        new MarkRadioDialog(this).builder()
                .setTitle(this.getResources().getString(R.string.bookmarks_style))
                .setCancelable(true)
                .setSingleChoiceItems(R.array.array_bookmarks_style,
                        this.mPreferences.getBookmarksStyle() - 1,
                        new RadioGroup.OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(RadioGroup group, int checkedId) {
                                mPreferences.setBookmarksStyle(checkedId + 1);
                                initTextView();
                            }
                        }).show();
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == 111) {
            if (grantResults[0] != 0) {
                LogUtils.w(TAG, "get no permission");
                return;
            }

            LogUtils.w(TAG, "get permission");
            if (this.operation == 0) {
                this.selectFile();
                return;
            }

            if (this.operation != 1) {
            } else {
                this.mBookmarkManager.exportBookmarks();

            }
        }
    }

    private void initTextView() {
        switch (this.mPreferences.getBookmarksStyle()) {
            case 1: {
                this.mStyleText.setText(this.getResources().getString(R.string.list));
                break;
            }
            case 2: {
                this.mStyleText.setText(this.getResources().getString(R.string.grid));
                break;
            }
            case 3: {
                this.mStyleText.setText(this.getResources().getString(R.string.grid_colorful));
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (resultCode != -1 || requestCode != 0) {
            super.onActivityResult(requestCode, resultCode, intent);
            return;
        }
        String v1 = FileUtils.getPath(this.mContext, intent.getData());
        if (v1 == null) {//不能导入
            ViewUtils.showToast(this.mContext.getResources().getString(R.string.import_bookmark_error), mContext);
        } else {
            File file = new File(v1);
            String fileType = FileUtils.getFileType(file);
            if (fileType.equalsIgnoreCase(".txt")) {
                this.mBookmarkManager.importBookmarksFromTxt(file);
            } else if (fileType.equalsIgnoreCase(".html")) {
                this.mBookmarkManager.importBookmarksFromHtml(file);
            } else {//不能导入
                ViewUtils.showToast(this.mContext.getResources().getString(R.string.import_bookmark_error), mContext);
            }

            super.onActivityResult(requestCode, resultCode, intent);
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.settings_bookmark);
        this.setToolbarTitle(R.string.settings_bookmark);

        this.mBookmarkManager = new BookmarkManager(this);
        this.mPreferences = PreferenceManager.getInstance();
        this.mStyleText = (TextView) this.findViewById(R.id.bookmarksStyleText);
        this.mContext = this;
        this.initTextView();
        ViewUtils.swipeToFinish(this.findViewById(R.id.settingLayout), this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    @SuppressLint(value = {"SdCardPath"})
    public void onSettingsItemClick(View v) {
        switch (v.getId()) {
            case R.id.layoutBookmarkStyle: {
                this.bookmarksStyleSelect();
                break;
            }
            case R.id.layoutExportBackup: {//导出书签到备份文件
                this.operation = 1;
                if (Utils.checkPermission(this.mContext, "android.permission.WRITE_EXTERNAL_STORAGE")
                        ) {
                    this.mBookmarkManager.exportBookmarks();
                    return;
                }

                Utils.requestPermission(this.mContext, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"});
                break;
            }
            case R.id.layoutImportBackup: {//从备份文件恢复书签
                this.operation = 0;
                if (Utils.checkPermission(this.mContext, "android.permission.WRITE_EXTERNAL_STORAGE")
                        ) {
                    this.selectFile();
                    return;
                }

                Utils.requestPermission(this.mContext, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"});
                break;
            }
        }
    }


    private void selectFile() {
        Intent intent = new Intent();
        intent.putExtra("HideFile", false);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath())),
                "*/*");
        intent.addCategory("android.intent.category.OPENABLE");
        intent.setClass(this, FileBrowser.class);
        this.startActivityForResult(intent, 0);
    }
}

